package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	//"google.golang.org/grpc/metadata"
	//"time"
	"traning/grpc_authentication/proto"
)

type coustomCredential struct{
}

func (this coustomCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error){
	return map[string]string{
		"appid": "970403",
	}, nil
}

func (this coustomCredential)RequireTransportSecurity() bool {
	return false
}

func main() {
	// 方式1
	//md := metadata.New(map[string]string{
	//	"appId": "970403",
	//})
	//interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	//	start := time.Now()
	//	err := invoker(ctx, method, req, reply, cc, opts...)
	//	if err != nil {
	//		panic(err)
	//	}
	//	fmt.Printf("request cost time %d" , time.Since(start))
	//	return nil
	//}
	//ctx := metadata.NewOutgoingContext(context.Background(), md)
	//conn, _ := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure(), grpc.WithUnaryInterceptor(interceptor))

	// 方式二

	conn, _ := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure(), grpc.WithPerRPCCredentials(coustomCredential{}))
	defer conn.Close()
	
	c := proto.NewTestServerClient(conn)
	res, err := c.GetClass(context.Background(), &proto.RequestData{Name:"ice"})
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Class)
}

